# coding=utf8
from bson import ObjectId

from models.search import model_search


def get_items(pid):
    last_id = None
    while True:
        res = model_search.get_list(1000, last_id=last_id, where={'Pid': pid})
        print(res.count(True))
        if res.count(True) < 1:
            break
        for item in res:
            yield item
            # print(item['_id'])
            last_id = item['_id']


if __name__ == '__main__':
    pids = ['57b13a9ac201c50667c84fc3']
    for pid in map(ObjectId, pids):
        res = ['标题,价格,销量']
        for item in get_items(pid):
            name = item['ItemName'].split("\n")[0].replace(',', ' ')
            res.append(
                ','.join([
                    name, str(item['Price']), str(item['SoldOut'])
                ])
            )
        with open("data/weidian_{pic}.csv".format(pic=str(pid)), 'w', encoding='utf-8-sig') as f:
            f.write(
                '\n'.join(res)
            )
